package com.pangu.converter.spring;

import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Linbizhao
 * @description: Spring对象转换工具类
 * @since 2023/11/24 11:24
 */
@Data
public class ConverterTools {

    public static <T> T convert(Class<T> clazz, Object object) {
        return Optional.ofNullable(object).map((o) -> {
            T obj = null;

            try {
                obj = clazz.newInstance();
                BeanUtils.copyProperties(o, obj);
            } catch (IllegalAccessException | InstantiationException var4) {
                var4.printStackTrace();
            }

            return obj;
        }).orElse(null);
    }

    public static <T, D> List<T> convert(Class<T> clazz, List<D> objList) {
        return (List) objList.stream().map((obj) -> {
            return convert(clazz, obj);
        }).collect(Collectors.toList());
    }
}
